package org.liang.zookeeper;

import java.util.Arrays;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ZookKeeperDemo {

    private static final String ROOT = "/root-ktv";

    private static final String ADDRESS = "localhost:2181";
    
    private static final int SESSIONTIMEOUT = 30000;
    
    public static void main(String[] args) throws Exception {
        // 创建一个与服务器的连接
        ZooKeeper zk = new ZooKeeper(ADDRESS, SESSIONTIMEOUT, new DemoWatcher());
        
        // 创建一个总的目录ktv，并不控制权限，这里需要用持久化节点，不然下面的节点创建容易出错
        zk.create(ROOT, "root-ktv".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        
        // 然后杭州开一个KTV , PERSISTENT_SEQUENTIAL 类型会自动加上 0000000000 自增的后缀
        zk.create(ROOT + "/杭州KTV", "杭州KTV".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.PERSISTENT_SEQUENTIAL);
       
        // 也可以在北京开一个, EPHEMERAL session 过期了就会自动删除
        zk.create(ROOT + "/北京KTV", "北京KTV".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.EPHEMERAL);
       
        // 同理，我可以在北京开多个，EPHEMERAL_SEQUENTIAL session 过期自动删除，也会加数字的后缀
        zk.create(ROOT + "/北京KTV-分店1", "北京KTV-分店1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.EPHEMERAL_SEQUENTIAL);
        // 同理，我可以在北京开多个，EPHEMERAL_SEQUENTIAL session 过期自动删除，也会加数字的后缀
        zk.create(ROOT + "/北京KTV-分店2", "北京KTV-分店2".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.EPHEMERAL_SEQUENTIAL);
        List<String> ktvs = zk.getChildren(ROOT, true);
        System.out.println(Arrays.toString(ktvs.toArray()));
        for (String node : ktvs) {
            zk.delete(ROOT + "/" + node, -1);  // 删除节点
        }
        // 根目录得最后删除的
        zk.delete(ROOT, -1);
        zk.close();
    }

}

class DemoWatcher implements Watcher{
    Logger logger = LoggerFactory.getLogger(DemoWatcher.class);
    @Override
    public void process(WatchedEvent event) {
        logger.debug("\n stat:{}, type:{}, wrapper:{}, path:{} ",
            new Object[] {event.getState(), event.getType(), event.getWrapper(), event.getPath()});
    }
}